world.querySelectorAll('.invisible').forEach((e) => { e.meshInvisible = true }) // 隐形墙（防止奶奶逃掉）
import i18n from '@root/i18n'

const MeshScale = new GameVector3(0.0625, 0.0625, 0.0625)
function spawn_granny() {//把生成僵尸的代码封装成函数
    const e = world.createEntity({
        mesh: 'mesh/GRANNY(梦魇).vb',
        meshScale: MeshScale,
        collides: true, // 开启碰撞
        gravity: true, // 开启重力
        friction: 0, // 关闭摩擦力
        position: new GameVector3(
            74.3, 22.4, 88.4
        ),
    });
    if (!e) return
    e.maxHp = 20;
    e.hp = 20;
    e.addTag('僵尸');
    e.enableDamage = true;
    e.onVoxelContact(({ x, y, z, voxel }) => {
        e.velocity.y = 0.3 + Math.random() * 0.7//碰到砖块就跳一下
    })
    e.onEntityContact(({ other }) => {
        if (other.player) {//僵尸撞到玩家
            if (other.hasTag('cannotdie')) return;
            if (other.hp <= 0) return;
            other.hurt(100)//对玩家造成伤害
            other.player.directMessage(i18n.t("granny_message", { lng: other.player.language, hp: other.hp, maxHp: other.maxHp }))
        }
    })
    e.onDie(async () => {
        e.destroy()
        world.say(i18n.t("granny_die_message", { lng: "en" }))
        await sleep(60000)
        spawn_granny()
    })
}

async function spawn_fish() {//把生成僵尸的代码封装成函数
    const e = world.createEntity({
        mesh: 'mesh/鳄鱼.vb',
        meshScale: MeshScale,
        collides: true, // 开启碰撞
        gravity: false, // 开启重力
        friction: 0, // 关闭摩擦力

        fixed: false,
        position: new GameVector3(
            8.8, 8.8, 8.2
        ),
    });
    // e.addTag('僵尸');
    if (!e) return
    e.maxHp = 10000;
    e.hp = 10000;
    e.addTag('鳄鱼')
    e.enableDamage = true;
    // e.onVoxelContact(({x,y,z,voxel})=>{
    //     e.velocity.y = 0.3+Math.random()*0.7//碰到砖块就跳一下
    // })
    e.onEntityContact(async ({ other }) => {
        if (other.player) {//僵尸撞到玩家
            if (other.hasTag('cannotdie')) return;
            if (other.hp <= 0) return;
            other.hurt(other.hp)//对玩家造成伤害
            other.player.directMessage(i18n.t("fish_message", { lng: other.player.language, hp: other.hp, maxHp: other.maxHp }))
        }
    })

    e.onDie(async () => {
        e.destroy()
        world.say(i18n.t("fish_die_message", { lng: "en" }))
        await sleep(1000)
        spawn_fish()
    })
    while (true) {
        if (e.position.y >= 9) {
            e.destroy()
            world.say(i18n.t("fish_back_message", { lng: "en" }))
            spawn_fish()
            break;
            return;
        }
        await sleep(640)
    }
}

function spawn_robot() {//把生成僵尸的代码封装成函数
    const e = world.createEntity({
        mesh: 'mesh/扫地机器人.vb',
        meshScale: MeshScale,
        collides: true, // 开启碰撞
        gravity: true, // 开启重力
        friction: 0, // 关闭摩擦力
        position: new GameVector3(
            70.6, 3.4, 49.7
        ),
    });
    if (!e) return
    e.maxHp = 20;
    e.hp = 20;
    e.addTag('僵尸');
    e.enableDamage = true;
    // e.onVoxelContact(({x,y,z,voxel})=>{
    //     e.velocity.y = 0.3+Math.random()*0.7//碰到砖块就跳一下
    // })
    e.onEntityContact(({ other }) => {
        if (other.player) {//僵尸撞到玩家
            if (other.hasTag('cannotdie')) return;
            if (other.hp <= 0) return;
            other.hurt(100)//对玩家造成伤害
            other.player.directMessage(i18n.t("robot_message", { lng: other.player.language, hp: other.hp, maxHp: other.maxHp }))
        }
    })
    e.onDie(async () => {
        e.destroy()
        world.say(i18n.t("robot_die_message", { lng: "en" }))
        await sleep(5000)
        spawn_robot()
    })
}

function spawn_grandpa() {//把生成僵尸的代码封装成函数
    const e = world.createEntity({
        mesh: 'mesh/GEANDPA.vb',
        meshScale: MeshScale,
        collides: true, // 开启碰撞
        gravity: true, // 开启重力
        friction: 0, // 关闭摩擦力
        position: new GameVector3(
            82, 32, 80
        ),
    });
    if (!e) return
    e.maxHp = 20;
    e.hp = 20;
    e.addTag('僵尸');
    e.enableDamage = true;
    e.onVoxelContact(({ x, y, z, voxel }) => {
        e.velocity.y = 0.3 + Math.random() * 0.7//碰到砖块就跳一下
    })
    e.onEntityContact(({ other }) => {
        if (other.player) {//僵尸撞到玩家
            if (other.hasTag('cannotdie')) return;
            if (other.hp <= 0) return;
            other.hurt(100)//对玩家造成伤害
            other.player.directMessage(i18n.t("grandpa_message", { lng: other.player.language, hp: other.hp, maxHp: other.maxHp }))
        }
    })
    e.onDie(async () => {
        e.destroy()
        world.say(i18n.t("grandpa_die_message", { lng: "en" }))
        await sleep(60000)
        spawn_grandpa()
    })
}
async function spawn_slendrina() {//把生成僵尸的代码封装成函数
    const e = world.createEntity({
        mesh: 'mesh/斯伦德里纳.vb',
        meshScale: MeshScale,
        collides: true, // 开启碰撞
        gravity: true, // 开启重力
        friction: 0, // 关闭摩擦力
        position: new GameVector3(
            71, 11.8, 82
        ),
    });
    if (!e) return
    e.maxHp = 20;
    e.hp = 20;
    e.addTag('僵尸');
    e.enableDamage = true;
    e.onVoxelContact(({ x, y, z, voxel }) => {
        e.velocity.y = 0.3 + Math.random() * 0.7//碰到砖块就跳一下
    })
    e.onEntityContact(({ other }) => {
        if (other.player) {//僵尸撞到玩家
            if (other.hasTag('cannotdie')) return;
            if (other.hasTag('摇篮')) return
            if (other.hp <= 0) return;
            other.hurt(100)//对玩家造成伤害
            other.player.directMessage(i18n.t("slendrina_message", { lng: other.player.language, hp: other.hp, maxHp: other.maxHp }))
        }
    })
    e.onDie(async () => {
        e.destroy()
        world.say(i18n.t("slendrina_die_message", { lng: "en" }))
        await sleep(15000)
        spawn_slendrina()
    })
    while (true) {
        if (e.position.y < 9.28) {
            e.destroy()
            world.say(i18n.t("slendrina_back_message", { lng: "en" }))
            spawn_slendrina()
            break;
            return;
        }
        await sleep(640)
    }
}
// for (let i = 0; i < 30; i++) {//开局生成一堆僵尸
spawn_granny()
spawn_grandpa()
spawn_slendrina()
spawn_robot()
spawn_fish()
// }
const Quat = new GameQuaternion(0, 0, 0, 1)// box引擎默认的旋转朝向
let allPlayers: any[] = []//所有玩家
let allZombies: any[] = []//所有僵尸
let allFish: any[] = [] //所有鳄鱼
world.onTick(async ({ tick }) => {//每秒16个tick
    if (tick % 16 === 0) {//每16个tick运行一次, 而不是每个tick都运行,节省性能
        allPlayers = world.querySelectorAll('.吸引')
        allFish = world.querySelectorAll('.鳄鱼')
    }
    allFish.forEach(async (e) => {
        let zomPos = e.position
        if (tick % 11 === 0) {//每11个tick运行一次, 而不是每个tick都运行,节省性能
            let target = allPlayers.sort((a, b) => {//僵尸寻找距离最近的玩家
                return a.position.distance(zomPos) - b.position.distance(zomPos)
            })[0]
            if (target) {//地图如果还有玩家
                e.target = target//让僵尸记住要追杀的玩家
            }
        }
        if (e.target && !e.target.destroyed) {//如果要追杀的玩家还没有离开地图
            var direction = e.target.position.sub(zomPos); //僵尸往玩家的方向矢量
            var dist = direction.mag() //矢量的长度
            var speed = 1.6//速度0.2~0.5随机
            e.velocity.x = direction.x * speed / dist
            e.velocity.z = direction.z * speed / dist
            // 让僵尸面向自己的前进方向
            var orientation = Quat.rotateY(Math.atan2(e.velocity.z, e.velocity.x))
            e.meshOrientation.copy(orientation)
        }
    })
})
world.onTick(async ({ tick }) => {//每秒16个tick
    if (tick % 16 === 0) {//每16个tick运行一次, 而不是每个tick都运行,节省性能
        allPlayers = world.querySelectorAll('.吸引')
        allZombies = world.querySelectorAll('.僵尸')
    }
    allZombies.forEach(async (e) => {
        let zomPos = e.position
        if (tick % 11 === 0) {//每11个tick运行一次, 而不是每个tick都运行,节省性能
            let target = allPlayers.sort((a, b) => {//僵尸寻找距离最近的玩家
                return a.position.distance(zomPos) - b.position.distance(zomPos)
            })[0]
            if (target) {//地图如果还有玩家
                e.target = target//让僵尸记住要追杀的玩家
            }
        }
        if (e.target && !e.target.destroyed) {//如果要追杀的玩家还没有离开地图
            var direction = e.target.position.sub(zomPos); //僵尸往玩家的方向矢量
            var dist = direction.mag() //矢量的长度
            var speed = 0.22//速度0.2~0.5随机
            e.velocity.x = direction.x * speed / dist
            e.velocity.z = direction.z * speed / dist
            // 让僵尸面向自己的前进方向
            var orientation = Quat.rotateY(Math.atan2(e.velocity.z, e.velocity.x))
            e.meshOrientation.copy(orientation)
        }
    })
})




// world.onPlayerJoin(async({ entity }) => {
//     entity.onFluidEnter(async() => {//当玩家掉到水里
//         entity.hurt(entity.maxHp)
//     })
// })
world.onPlayerJoin(async ({ entity }) => {
    entity.enableDamage = true;
    entity.onDie(async () => {
        // 直接根据玩家语言设置空手状态文本
        entity.onHand = entity.player.language === 'en' ? 'Nothing' : '空气'
        // entity.wq = 0
        world.say(i18n.t("player_die_message_1", { lng: "en", playerName: entity.player.name }))
        await sleep(3000)
        // entity.setPet()
        // 空中随机位置复活
        entity.position.copy(entity.player.spawnPoint)
        await sleep(100) // 防止引擎延迟造成复活后受到死前的伤害
        entity.hp = entity.maxHp //恢复满血
        entity.day += 1
        if (entity.day > 3) {
            world.say(i18n.t("player_die_message_2", { lng: "en", playerName: entity.player.name }))
            entity.player.invisible = true
            entity.player.showName = false
            entity.player.canFly = true
            entity.player.spectator = true
            entity.removeTag('吸引')
            entity.wq = 0
            return;
        }
        await entity.player.dialog({
            type: GameDialogType.TEXT,
            content: i18n.t("day_content", { lng: entity.player.language, day: entity.day }),
        })
        entity.player.walkSpeed -= 0.05
        entity.player.runSpeed -= 0.05
        if (entity.day == 2) {
            await entity.player.dialog({
                type: GameDialogType.TEXT,
                title: i18n.t("player_thought_title", { lng: entity.player.language }),
                content: i18n.t("player_thought_content_1", { lng: entity.player.language }),
            })
        }
        else if (entity.day == 3) {
            await entity.player.dialog({
                type: GameDialogType.TEXT,
                title: i18n.t("player_thought_title", { lng: entity.player.language }),
                content: i18n.t("player_thought_content_2", { lng: entity.player.language }),
            })
        }
    })
})
world.onClick(async ({ entity, clicker }) => {
    if (entity.isPlayer) return;
    if (clicker.wq) {
        if (entity.hasTag('鳄鱼')) return
        entity.hurt(clicker.wq) //被点中的实体会掉血
    }
})


world.onPlayerJoin(async ({ entity }) => {
    entity.addTag('吸引')
    entity.bq = []
})


